import { Component, OnInit, Injector, ViewChild, EventEmitter, Output } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/primeng';
import {
    ListDtoExtensionsItem,
    Stock_AccountBaseListDto,
    StockZT_TransfersBillItemServiceProxy,
    StockZT_RoomServiceProxy,
    StockZT_MaintainBillItemServiceProxy,
    Stock_MaintainToolItemListDto,
    Stock_MaintainToolBaseEditDto,
    StockZT_OutBillItemServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { UserDataPermissionServiceProxy, SessionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { finalize } from 'rxjs/operators';
@Component({
    templateUrl: './create-or-edit-tool-maintain-bill-item-modal.component.html',
    animations: [appModuleAnimation()],
    selector: 'createOrEditToolMaintainBillModal'
})
export class CreateOrEditToolMaintainBillModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _base_SessionServiceProxy: SessionServiceProxy,
        private _billService: StockZT_MaintainBillItemServiceProxy,
        private _intobillService: StockZT_OutBillItemServiceProxy,
        private _tranbillService: StockZT_TransfersBillItemServiceProxy,
        private _userDataPermissionService: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy
    ) {
        super(injector);
    }
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() modalUpdate: EventEmitter<any> = new EventEmitter<any>();
    @Output() accountShow: EventEmitter<any> = new EventEmitter<any>();
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    f_currentDept; //当前部门
    selectedOutLearder; //审核领导
    optionOutLearder;
    optionInDept;
    selectedInDept; //调入单位
    optionInKeeper;
    selectedInKeeper; //调入单位保管员
    optionInAccounting;
    selectedInAccounting; //调度单位会计
    selectedBill: Array<Stock_MaintainToolItemListDto>;
    editBill: Stock_MaintainToolItemListDto;
    billbase = new Stock_MaintainToolBaseEditDto();
    f_TargetRoomNameOptions;
    miliOutBillList = new Array<Stock_MaintainToolItemListDto>();
    f_MaterialTypeOptions;
    recipientsNatureOptions;
    userDataPermissions;
    selectedDepts;
    itemid;
    qccard;
    saving = false;
    closed = false;
    active = false;
    billid;
    roomOption;
    f_TargetLocationNameOption = [];
    f_Warehouse;
    f_StorageArea;
    ngOnInit() {
        this._billService.getWarehouseCombobox('工具库').subscribe(result => {
            this.roomOption = result.items.map(e => {
                return {
                    lable: e.displayText,
                    value: e.value
                };
            });
        });
        this._intobillService.getDeptIdByDeptCode('天津火箭').subscribe(result1 => {
            this._tranbillService.getRoleUser('设备技术员', result1.toString()).subscribe(result => {
                this.optionOutLearder = result.items.map(e => {
                    return {
                        label: e.displayText,
                        value: e
                    };
                });
            });
        });
        this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
            this.f_currentDept = result.value; //当前登录人所在单位
            this.billbase.f_Dept = this.f_currentDept;
            this._tranbillService.getRoleUser('物流管理员', result.value).subscribe(result => {
                this.optionInAccounting = result.items.map(e => {
                    return {
                        label: e.displayText,
                        value: e
                    };
                });
            });
        });

        this._userDataPermissionService.getUserDataPermissionsForEdit(undefined).subscribe(result => {
            this.optionInDept = result.allDepts.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            this.selectedInDept = result.allDepts;
        });
    }
    getStorage(index) {

        this._billService.getStorageAreaCombobox(this.miliOutBillList[index].f_TargetRoomCode).subscribe(result => {

            this.f_TargetLocationNameOption[index] = result.items.map(e => {
                return {
                    lable: e.displayText,
                    value: e.value
                };
            });

            if (this.f_TargetLocationNameOption[index] != undefined && this.f_TargetLocationNameOption[index].length > 0) {
                this.miliOutBillList[index].f_TargetLocationCode = this.f_TargetLocationNameOption[index][0].value;
            }

        });
    }
    // getStorageInfo(index) {
    //     this.miliOutBillList[index].f_TargetLocationCode = this.f_StorageArea;
    // }
    //从台帐新增工具室维修数据
    showList(selectedAccounts: Array<Stock_AccountBaseListDto>): void {
        // var keepGo = true;
        // selectedAccounts.forEach(element => {
        //     if (element.f_UsableSum! <= 0 && keepGo == true) {
        //         keepGo = false;
        //         this.message.warn('可用合计必须大于0！');
        //     }
        // });
        if (selectedAccounts.some(pg => pg.f_UsableSum <= 0)) {
            this.message.warn('可用合计必须大于0！');
            return;
        }
        this._stockZT_RoomServiceProxy.checkCurrentUserDept(selectedAccounts).subscribe(result => {
            if (!result) {
                this.message.warn('只能选择用户所属部门！');
            } else {
                this.active = true;
                this.addAccoutInfo(selectedAccounts);
                this.modal.show();
            }
        });
        // if (keepGo) {
        // this.active = true;
        // this.addAccoutInfo(selectedAccounts);
        // this.modal.show();
        // }
    }
    show(id?: string, billitem?: Stock_MaintainToolItemListDto): void {
        this.closed = false;
        this.active = true;
        this.billid = id;
        if (billitem != null || billitem != undefined) {
            this._billService.getStorageAreaCombobox(billitem.f_TargetRoomCode).subscribe(result => {
                this.f_TargetLocationNameOption[this.miliOutBillList.length] = result.items.map(e => {
                    return {
                        lable: e.displayText,
                        value: e.value
                    };
                });
            });
            this.itemid = billitem.id;
            this.editBill = billitem;
            //  billitem.f_Sort = 0;
            this.miliOutBillList.push(this.editBill);

        }

        this._billService.getMaintainToolBaseForEdit(id).subscribe(result => {
            this.billbase = result;

            this.modal.show();
        });
    }

    changeInAccounting() {
        this._userDataPermissionService.getUserDataPermissions('Warehouses').subscribe(result => {
            // this.itemContextMenuItems = this.getContextMenuItems();
            this._stockZT_RoomServiceProxy
                .getRoomList('工具库', result.items, this.selectedInDept.displayText, undefined, 1000, 0)
                .subscribe(result => {
                    this.f_TargetRoomNameOptions = result.items.map(e => {
                        return {
                            label: e.f_WarehouseName,
                            value: e
                        };
                    });
                });
        });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getqccard(event) {
        this.qccard = event;
    }

    onHidden() {
        this.closed = true;
    }

    accountmodalshow() {
        this.close();

        let timer = setInterval(() => {
            if (this.closed) {
                this.accountShow.emit(event);
                clearInterval(timer);
            }
        }, 50);
    }

    delete() {
        if (!this.selectedBill) {
            this.notify.error('请先勾选对应的物料信息');
            return;
        }

        this.selectedBill.forEach(element => {
            let milioutbill = new Stock_MaintainToolItemListDto();
            milioutbill = _.filter(this.miliOutBillList, { f_Sort: element.f_Sort })[0];
            _.remove(this.miliOutBillList, milioutbill);
        });

        this.selectedBill = null;
    }

    addAccoutInfo(event: Array<Stock_AccountBaseListDto>) {
        if (event) {
            event.forEach(element => {
                if (!this.miliOutBillList.find(e => element.f_MaterialCode == e.f_MaterialCode)) {
                    let milioutbill = new Stock_MaintainToolItemListDto();
                    milioutbill.f_MaterialCode = element.f_MaterialCode;
                    milioutbill.f_MaterialName = element.f_MaterialName;
                    milioutbill.f_StorageAreaName = element.f_StorageAreaName;
                    milioutbill.f_StorageAreaCode = element.f_StorageAreaCode;
                    milioutbill.f_Sort = this.miliOutBillList.length;
                    milioutbill.f_UnitPrice = element.f_Price;
                    milioutbill.f_Unit = element.f_UnitId;
                    milioutbill.f_TradeMark = element.f_TradeMark;
                    milioutbill.f_Specification = element.f_Specification;
                    milioutbill.f_WarehouseName = element.f_WarehouseName;
                    milioutbill.f_WarehouseCode = element.f_WarehouseCode;
                    milioutbill.f_AccountId = element.id;
                    milioutbill.f_RealUsable = element.f_RealUsable;
                    milioutbill.f_InventSerialID = element.f_InventSerialID;
                    if (this.roomOption.length > 0) {
                        milioutbill.f_TargetRoomCode = this.roomOption[0].value;
                    }

                    this.miliOutBillList.push(milioutbill);
                    this.f_TargetLocationNameOption[this.miliOutBillList.length - 1] = new Array();

                    if (milioutbill.f_TargetRoomCode != undefined) {
                        this.getStorage(this.miliOutBillList.length - 1);
                    }
                }
            });
        }
        this.show(this.billid, undefined);
    }

    cancel(): void {
        this.close();
        this.miliOutBillList = new Array<Stock_MaintainToolItemListDto>();
    }

    save(): void {
        this.saving = true;
        if (this.miliOutBillList.some(pg => pg.f_RealUsable < pg.f_Quantity)) {
            this.notify.error('维修数量不能大于实际可用！');
            this.saving = false;
            return;
        }
        if (this.miliOutBillList.some(element => element.f_Quantity == undefined || element.f_Quantity <= 0)) {
            this.notify.error(this.l('维修数量不正确！'));
            this.saving = false;
            return;
        }
        this.billbase.f_AuditLeaderId = this.selectedOutLearder.value;
        this.billbase.f_AuditLeader = this.selectedOutLearder.displayText;
        this.billbase.f_AuditAccount = this.selectedInAccounting.displayText;
        this.billbase.f_AuditAccountId = this.selectedInAccounting.value;
        // this.billbase.f_AuditStoremanId = this.selectedInKeeper.value;
        // this.billbase.f_AuditStoreman = this.selectedInKeeper.displayText;
        this.billbase.f_ToDept = '设备工装处';
        this.billbase.f_ToDeptId = 7;
        this.billbase.f_BillName = this.billbase.f_Dept + '工具室维修';
        this._billService.createOrUpdateMaintainToolBase(this.billbase).subscribe(result => {
            this.billbase.id = result;
            this._billService.creatWorkflowOfTool(this.billbase).subscribe(() => {
                this._billService.creatMaintainToolItems(this.miliOutBillList, result).pipe(
                    finalize(() => {
                        this.saving = false;
                    })
                ).subscribe(() => {
                    if (this.itemid != null && this.itemid != undefined) {
                        this._billService.deleteMaintainBillItem(this.itemid).pipe(
                            finalize(() => {
                                this.saving = false;
                            })
                        ).subscribe(() => {
                            this.notify.success(this.l('更新成功'));
                            this.modalSave.emit(this.billid);
                            this.billid = undefined;
                            this.itemid = undefined;
                        });
                    } else {
                        this.notify.success(this.l('提交成功'));
                        this.modalSave.emit(this.billid);
                        this.billid = undefined;
                        this.itemid = undefined;
                    }
                    this.miliOutBillList = new Array<Stock_MaintainToolItemListDto>();
                    this.close();
                });
            });
        });
    }
}
